home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 3531 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.0 KB

  1. Path: cymbal.aix.calpoly.edu!not-for-mail
  2. From: dstubbs@cymbal.aix.calpoly.edu (Dan Stubbs)
  3. Newsgroups: comp.lang.c
  4. Subject: Display an int justified with embedded commas.
  5. Date: 29 Jan 1996 09:17:08 -0800
  6. Organization: California Polytechnic State University, San Luis Obispo
  7. Message-ID: <4eivek$16qu@cymbal.aix.calpoly.edu>
  8. NNTP-Posting-User: dstubbs@cymbal.aix.calpoly.edu
  9.  
  10. The following code displays an int right justified in width
  11. columns (if width is big enough) and with embedded commas.
  12.  
  13. Is there a better (more concise) way to do this?
  14.  
  15. /*------------------------------------------------------------------*/
  16. void comma_print (unsigned int x) {
  17.     if (x > 999) {
  18.         comma_print (x / 1000);
  19.         printf (",%03d", x % 1000);
  20.     } else printf ("%d", x);
  21. }
  22.  
  23. void int_print (int x, int width) {
  24.     int len = 1, m = (x < 0),v,n;
  25.     v = n = (m ? -x : x);
  26.  
  27.     while ((n /= 10) > 0) len++;
  28.     len += (len - 1) / 3 + (m ? 1 : 0);
  29.     for (n = len; n < width; n++) putchar (' ');
  30.     if (m) putchar ('-');
  31.     comma_print (v);
  32. }
  33. /*------------------------------------------------------------------*/
  34.